/**
 * Copyright (c) Daniel Centore
 *
 * ex: set filetype=java expandtab tabstop=4 shiftwidth=4 :
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * This code is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation.
 */
package ronp.anim.data.objects;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.geom.AffineTransform;

import javax.swing.ImageIcon;

import ronp.anim.data.Grip;

/**
 * Represents a simple image on the screen. Basically just the two corners of the image.
 * 
 * @author Daniel Centore
 *
 */
public class RNSimpleImage extends RNObject
{
	private static final long serialVersionUID = 1L;

	private Grip start; // The start of the image
	private Grip end; // The end of the image
	private ImageIcon image; // The image to display (serializable)
	private transient Image img = null; // The image to display (not serializable)

	public RNSimpleImage(Grip start, Grip end, ImageIcon image)
	{
		addGrips(start, end);

		this.start = start;
		this.end = end;
		this.image = image;
	}

	@Override
	public void drawImage(int frame, Graphics2D g2, boolean selected)
	{
		if (img == null)
			img = image.getImage();

		Point p1 = start.getPosition(frame);
		Point p2 = end.getPosition(frame);

		if (p1 == null)
			return;

		AffineTransform at = new AffineTransform();
		at.translate(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y));
		at.scale((double) Math.abs(p1.x - p2.x) / img.getWidth(null), (double) Math.abs(p1.y - p2.y) / img.getHeight(null));
		if (p2.x > p1.x)
		{
			at.translate(img.getWidth(null), 0);
			at.scale(-1, 1);
		}

		if (p2.y > p1.y)
		{
			at.translate(0, img.getHeight(null));
			at.scale(1, -1);
		}

		if (selected)
		{
			g2.setColor(Color.red);
			g2.drawRect(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y), Math.abs(p1.x - p2.x), Math.abs(p1.y - p2.y));
		}

		g2.drawImage(img, at, null);
	}

	@Override
	public String toString()
	{
		return "Simple Image";
	}
}
